package cn.zorbus.laian.domain.service;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.opencv.opencv_core.Mat;
import org.bytedeco.opencv.opencv_videoio.VideoCapture;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.nio.file.Paths;

import static org.bytedeco.opencv.global.opencv_imgcodecs.imwrite;

@Slf4j
public class VideoScreenshotService implements IVideoCaptureService{

    public String screenshot(String videoFilePath) {
        String screenshotPath = videoFilePath + "-SCREENSHOT" + ".png";
        // 本地视频截图是否存在?存在就返回
        if (FileUtil.exist(screenshotPath)) {
            return videoFilePath + "-SCREENSHOT" + ".png";
        }
        Path videoPath = Paths.get(videoFilePath);
        // 打开视频文件
        try (VideoCapture videoCapture = new VideoCapture(videoPath.toString());) {
            // 检查视频是否成功打开
            if (!videoCapture.isOpened()) {
                log.info("Error opening video file.");
                return "";
            }
            // 创建一个Mat对象来保存每一帧的图像数据
            Mat frame = new Mat();
            // 视频帧索引
            // 循环读取视频帧
            videoCapture.read(frame);
            // 检查是否到达视频末尾
            if (frame.empty()) {
                log.debug("End of video");
                return "";
            }
            // 处理每一帧，例如保存为图像文件
            saveFrameAsImage(frame, screenshotPath);
            return screenshotPath;
        }
    }

    private void saveFrameAsImage(Mat frame, String outputImagePath) {
        // 将Mat保存为图像文件
        imwrite(outputImagePath, frame);
        log.info("Saved frame to: {}", outputImagePath);
    }
}
